package com.itheima.easy.handler.wechat;

import com.alibaba.fastjson.JSONObject;
import com.itheima.easy.client.wechat.Config;
import com.itheima.easy.client.wechat.Factory;
import com.itheima.easy.client.wechat.response.CloseResponse;
import com.itheima.easy.client.wechat.response.QueryResponse;
import com.itheima.easy.client.wechat.response.RefundResponse;
import com.itheima.easy.config.wechat.WechatPayConfig;
import com.itheima.easy.constant.SuperConstant;
import com.itheima.easy.constant.TradeConstant;
import com.itheima.easy.enums.TradeEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.CommonPayHandler;
import com.itheima.easy.utils.*;
import com.itheima.easy.vo.RefundRecordVo;
import com.itheima.easy.vo.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName BasicPayHandlerImpl.java
 * @Description 微信交易基础类
 */
@Service
@Slf4j
public class WechatCommonPayHandler implements CommonPayHandler {


    @Autowired
    WechatPayConfig wechatPayConfig;

    @Override
    public TradeVo queryTrade(TradeVo tradeVo) {
        //1、获得微信客户端
        Config config = wechatPayConfig.config();
        //3、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //4、指定配置文件
        Factory factory = new Factory();
        factory.setOptions(config);
        //5、调用接口
        try {
            QueryResponse queryResponse = factory.Common()
                    .query(String.valueOf(tradeVo.getTradeOrderNo()));
            //6、判断响应是否成功
            boolean success = ResponseChecker.success(queryResponse);
            //7、响应成功，分析交易状态
            boolean flag = true;
            if (success&&!EmptyUtil.isNullOrEmpty(queryResponse.getTradeState())){
                //SUCCESS：支付成功,REFUND：转入退款,NOTPAY：未支付,CLOSED：已关闭,REVOKED：已撤销（仅付款码支付会返回）
                //USERPAYING：用户支付中（仅付款码支付会返回）,PAYERROR：支付失败（仅付款码支付会返回）
                switch (queryResponse.getTradeState()){
                    case TradeConstant.WECHAT_TRADE_CLOSED:
                        tradeVo.setTradeState(TradeConstant.TRADE_CLOSED);break;
                    case TradeConstant.WECHAT_TRADE_REVOKED:
                        tradeVo.setTradeState(TradeConstant.TRADE_CLOSED);break;
                    case TradeConstant.WECHAT_TRADE_SUCCESS:
                        tradeVo.setTradeState(TradeConstant.TRADE_SUCCESS);break;
                    case TradeConstant.WECHAT_TRADE_REFUND:
                        tradeVo.setTradeState(TradeConstant.TRADE_SUCCESS);break;
                    default:
                        flag = false;break;
                }
                //8、修改交易单状态
                if (flag){
                    tradeVo.setResultCode(queryResponse.getTradeState());
                    tradeVo.setResultMsg(queryResponse.getTradeStateDesc());
                    tradeVo.setResultJson(JSONObject.toJSONString(queryResponse));
                    return tradeVo;
                }else {
                    log.info("查询微信交易单：{},结果：{}", tradeVo.getTradeOrderNo(),queryResponse.getTradeState());
                }
            }else {
                throw new RuntimeException("查询微信统一下单失败！");
            }
        } catch (Exception e) {
            log.warn("查询微信统一下单失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("查询微信统一下单失败！");
        }
        return tradeVo;
    }

    @Override
    public TradeVo refundTrade(TradeVo tradeVo) {
        //1、生成退款请求编号
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1,1);
        tradeVo.setOutRequestNo(String.valueOf(snowflakeIdWorker.nextId()));
        //2、获得微信客户端
        Config config = wechatPayConfig.config();
        //3、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //4、指定配置文件
        Factory factory = new Factory();
        factory.setOptions(config);
        //5、调用接口
        try {
            RefundResponse refundResponse = factory.Common()
                .refund(String.valueOf(tradeVo.getTradeOrderNo()),
                String.valueOf(tradeVo.getOperTionRefund()),
                tradeVo.getOutRequestNo(),String.valueOf(tradeVo.getTradeAmount()));
            boolean success = ResponseChecker.success(refundResponse);
            if (success&&String.valueOf(tradeVo.getTradeOrderNo()).equals(refundResponse.getOutTradeNo())){
                //6、指定此交易单是否有退款：YES
                tradeVo.setIsRefund(SuperConstant.YES);
                tradeVo.setRefund(tradeVo.getRefund().add(tradeVo.getOperTionRefund()));
                //7、保存退款单信息
                RefundRecordVo refundRecordVo = RefundRecordVo.builder()
                    .enterpriseId(tradeVo.getEnterpriseId())
                    .storeId(tradeVo.getStoreId())
                    .refundNo(tradeVo.getOutRequestNo())
                    .refundAmount(tradeVo.getOperTionRefund())
                    .refundCode(refundResponse.getCode())
                    .refundMsg(refundResponse.getMessage())
                    .productOrderNo(tradeVo.getProductOrderNo())
                    .tradeChannel(tradeVo.getTradeChannel())
                    .tradeOrderNo(tradeVo.getTradeOrderNo())
                    .memo("退款："+tradeVo.getMemo())
                    .build();
                switch (refundResponse.getStatus()){
                    case TradeConstant.WECHAT_REFUND_SUCCESS:
                        refundRecordVo.setRefundStatus(TradeConstant.REFUND_STATUS_SUCCESS);break;
                    case TradeConstant.WECHAT_REFUND_CLOSED:
                        refundRecordVo.setRefundStatus(TradeConstant.REFUND_STATUS_CLOSED);break;
                    case TradeConstant.WECHAT_REFUND_PROCESSING:
                        refundRecordVo.setRefundStatus(TradeConstant.REFUND_STATUS_SENDING);break;
                    default:
                        refundRecordVo.setRefundStatus(TradeConstant.REFUND_STATUS_FAIL);break;
                }
            }else {
                log.error("网关：微信统一下单退款失败：{},结果：{}", tradeVo.getTradeOrderNo(),
                        JSONObject.toJSONString(refundResponse));
                throw new RuntimeException("网关：微信统一下单退款失败!");
            }
        } catch (Exception e) {
            log.error("微信统一下单退款失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradeEnum.TRAD_REFUND_FAIL);
        }
        return BeanConv.toBean(tradeVo, TradeVo.class);
    }

    @Override
    public RefundRecordVo queryRefundTrade(RefundRecordVo refundRecordVo) {
        //1、获得微信客户端
        Config config = wechatPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //3、指定配置文件
        Factory factory = new Factory();
        factory.setOptions(config);
        try {
            RefundResponse refundResponse = factory.Common().queryRefund(refundRecordVo.getRefundNo());
            //4、判断响应是否成功
            boolean success = ResponseChecker.success(refundResponse);
            //5、查询出的退款状态
            if (success&&TradeConstant.WECHAT_REFUND_SUCCESS.equals(refundResponse.getStatus())){
                refundRecordVo.setRefundStatus(TradeConstant.REFUND_STATUS_SUCCESS);
                refundRecordVo.setRefundCode(refundResponse.getCode());
                refundRecordVo.setRefundMsg(refundResponse.getMessage());
            }else {
                log.error("网关：查询微信统一下单退款失败：{},结果：{}", refundRecordVo.getTradeOrderNo(),
                    JSONObject.toJSONString(refundResponse));
                throw new RuntimeException("网关：查询微信统一下单退款失败！");
            }
        } catch (Exception e) {
            log.warn("查询微信统一下单退款失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("查询微信统一下单退款失败！");
        }
        return refundRecordVo;
    }

    @Override
    public TradeVo closeTrade(TradeVo tradeVo) {
        //1、获得微信客户端
        Config config = wechatPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //3、使用配置
        Factory factory = new Factory();
        factory.setOptions(config);
        try {
            //4、调用三方API关闭订单
            CloseResponse closeResponse = factory.Common()
                .close(String.valueOf(tradeVo.getTradeOrderNo()));
            //5、关闭订单受理情况
            boolean success = ResponseChecker.success(closeResponse);
            if (success){
                tradeVo.setTradeState(TradeConstant.TRADE_CLOSED);
                return tradeVo;
            }else {
                log.error("网关：微信关闭订单失败：{},结果：{}", tradeVo.getTradeOrderNo(),
                    JSONObject.toJSONString(closeResponse));
                throw  new RuntimeException("网关：微信关闭订单失败!");
            }
        } catch (Exception e) {
            log.warn("微信关闭订单失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw  new ProjectException(TradeEnum.TRAD_CLOSE_FAIL);
        }
    }

    @Override
    public TradeVo downLoadBill(TradeVo tradeVo) {
        //toDo 后面补齐
        throw  new RuntimeException("未支持：微信关下载账单!");
    }


}
